import { Routes, Route } from "react-router-dom";
import Home from "@/pages/Home";
import { useState } from "react";
import { AuthContext, UserInfo, UserRole } from '@/contexts/authContext';
import { toast } from "sonner";
import Login from "@/pages/Login";
import Register from "@/pages/Register";
import ProductDetail from "@/pages/ProductDetail";
import PostProduct from "@/pages/PostProduct";
import Cart from "@/pages/Cart";
import OrderList from "@/pages/OrderList";
import UserProfile from "@/pages/UserProfile";
import AdminDashboard from "@/pages/admin/Dashboard";
import AdminProducts from "@/pages/admin/Products";
import AdminUsers from "@/pages/admin/Users";
import AdminOrders from "@/pages/admin/Orders";
import MerchantDashboard from "@/pages/merchant/Dashboard";
import MerchantProducts from "@/pages/merchant/Products";
import MerchantOrders from "@/pages/merchant/Orders";
import Layout from "@/components/Layout";
import PrivateRoute from "@/components/PrivateRoute";

// 模拟数据 - 用户信息
const mockUsers = [
  { id: '1', username: 'student1', password: '123456', role: 'student' as UserRole },
  { id: '2', username: 'admin', password: 'admin123', role: 'admin' as UserRole },
  { id: '3', username: 'merchant1', password: 'merchant123', role: 'merchant' as UserRole },
];

export default function App() {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);

  // 登录处理
  const login = async (username: string, password: string): Promise<boolean> => {
    // 模拟API请求
    const user = mockUsers.find(u => u.username === username && u.password === password);
    
    if (user) {
      setIsAuthenticated(true);
      setUserInfo({
        id: user.id,
        username: user.username,
        role: user.role,
        campus: user.role === 'student' ? '主校区' : undefined
      });
      localStorage.setItem('userInfo', JSON.stringify(user));
      toast.success('登录成功');
      return true;
    } else {
      toast.error('用户名或密码错误');
      return false;
    }
  };

  // 注册处理
  const register = async (username: string, password: string, role: UserRole): Promise<boolean> => {
    // 检查用户名是否已存在
    if (mockUsers.some(u => u.username === username)) {
      toast.error('用户名已存在');
      return false;
    }
    
    // 模拟注册成功
    const newUser = {
      id: Date.now().toString(),
      username,
      password,
      role
    };
    
    // 在实际应用中，这里应该调用API存储用户信息
    mockUsers.push(newUser);
    
    toast.success('注册成功，请登录');
    return true;
  };

  // 登出处理
  const logout = () => {
    setIsAuthenticated(false);
    setUserInfo(null);
    localStorage.removeItem('userInfo');
    toast.success('已退出登录');
  };

  return (
    <AuthContext.Provider
      value={{ isAuthenticated, userInfo, setIsAuthenticated, setUserInfo, logout, login, register }}
    >
      <Routes>
        {/* 公共路由 */}
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        
        {/* 需要布局的路由 */}
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="product/:id" element={<ProductDetail />} />
          
          {/* 私有路由 - 需要登录 */}
          <Route element={<PrivateRoute />}>
            <Route path="post-product" element={<PostProduct />} />
            <Route path="cart" element={<Cart />} />
            <Route path="orders" element={<OrderList />} />
            <Route path="profile" element={<UserProfile />} />
            
            {/* 管理员路由 */}
            <Route path="admin" element={<PrivateRoute allowedRoles={['admin']} />}>
              <Route index element={<AdminDashboard />} />
              <Route path="products" element={<AdminProducts />} />
              <Route path="users" element={<AdminUsers />} />
              <Route path="orders" element={<AdminOrders />} />
            </Route>
            
            {/* 商家路由 */}
            <Route path="merchant" element={<PrivateRoute allowedRoles={['merchant']} />}>
              <Route index element={<MerchantDashboard />} />
              <Route path="products" element={<MerchantProducts />} />
              <Route path="orders" element={<MerchantOrders />} />
            </Route>
          </Route>
        </Route>
      </Routes>
    </AuthContext.Provider>
  );
}
